package com.woniu.filters;

import com.woniu.utils.MyJsonWebToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT过滤器
 *
 * @author WenXin
 * @version 1.0
 * @description: 拦截前端放过来的请求
 * @date 2022/9/6 11:07
 */
@Component
public class JWTFilter extends BasicHttpAuthenticationFilter {
    //前端封装token的key 固定写法
    private final String TOKENKEY = "Authorization";

    //配置全局跨域问题
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        response1.setHeader("Access-Control-Allow-Origin", request1.getHeader("Origin"));
        //OPTIONS就是预提交，浏览器发送的一个额外的请求，检查请求是否通常
        response1.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response1.setHeader("Access-Control-Allow-Headers", request1.getHeader("Access-Control-Request-Headers"));
        //如果是预提交的请求，我们直接返回一个正常状态即可
        if (request1.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response1.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request1, response1);
    }

    //shiro过滤的三大步骤 isAccessAllowed  isLoginAttempt  executeLogin
    //第一步 真正的Shiro的过滤器，第一步操作 是否允许访问 isAccessAllowed --> isLoginAttempt ---> executeLogin
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //重写isLoginAttempt方法
        if (isLoginAttempt(request, response)) {
            //进入说明登录认证成功
            try {
                //执行登录操作
                executeLogin(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response401(request, response);
                return false;
            }
        } else {
            response401(request, response);
        }
        return true;
    }

    //认证失败的跳转方法
    private void response401(ServletRequest request, ServletResponse response) {
        HttpServletResponse response1 = (HttpServletResponse) response;
        //重定向
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //第二步

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        String token = request1.getHeader(TOKENKEY);
        //判断请求头是否封装了token
        return token != null;
    }
    //第三步 执行subject.login()方法

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //获取token
        String token = request1.getHeader(TOKENKEY);
        //获取Subject对象。执行login认证方法
        getSubject(request, response).login(new MyJsonWebToken(token));
        //以上方法如果失败讲抛出异常AuthenticationException;
        return true;

    }
}
